package cqut;

public class Test {
    public static void main(String[] args) {
        Produce produce = new Produce();
        new Thread(() -> {
            for (; ; ) {
                try {
                    produce.in();
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "甲");

        new Thread(() -> {
            for (; ; )
                try {
                    produce.out();
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
        }, "A");
        new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i < 10; i++) {
                    try {
                        produce.out();
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }, "B");
    }
}

class Produce {
    int produce = 0;

    synchronized public void in() throws InterruptedException {
        if (produce == 0) {
            produce++;
            System.out.println(Thread.currentThread().getName() + "：0->1");
        } else {
            wait();
        }
    }

    synchronized public void out() throws InterruptedException {
        if (produce == 1) {
            produce--;
            System.out.println(Thread.currentThread().getName() + "：1->0");
        } else
            wait();
    }

}